package smallfrench.moteur.noeuds;

import java.util.Iterator;

import smallfrench.moteur.biblio.AIterable;
import smallfrench.moteur.biblio.RRien;
import smallfrench.moteur.interp.Portee;
import smallfrench.moteur.interp.RObjet;
import smallfrench.moteur.interp.err.ExceptionSortieBoucle;
import smallfrench.moteur.lexer.lexemes.Lexeme;

public class NPourchaque extends Noeud {

	private final String nomElement;
	private final Noeud noeudIterable;
	private final Noeud noeudRepetition;

	public NPourchaque(Lexeme t,
			String nomElement,
			Noeud noeudIterable,
			Noeud noeudRepetition) {

		super(t);

		this.nomElement = nomElement;
		this.noeudIterable = noeudIterable;
		this.noeudRepetition = noeudRepetition;
	}

	@Override
	public RObjet evaluer(Portee porteeParente) {

		Portee portee = new Portee(porteeParente);

		RObjet o = noeudIterable.evaluer(portee);

		Iterator<RObjet> iterator = AIterable.getIterateur(o);

		o = RRien.RIEN;

		for (; iterator.hasNext();) {

			RObjet i = iterator.next();

			portee.ajouterVariable(nomElement, i);

			try {
				o = noeudRepetition.evaluer(portee);
			} catch (ExceptionSortieBoucle t) {
				return o;
			}

		}
		return o;
	}

	@Override
	public String toString() {
		return "pourchaque " + nomElement + " dans (" + noeudIterable + ") " +
				noeudRepetition;
	}

}
